package ext.tianma.part.resolution;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import ext.com.iba.IBAUtil;
import ext.tianma.part.PartCommands;
import ext.tianma.workflow.BomWorkFlowUtil;
import wt.doc.WTDocumentHelper;
import wt.fc.ObjectReference;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.part.WTPartConfigSpec;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartStandardConfigSpec;
import wt.project.Role;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionServerHelper;
import wt.team.Team;
import wt.team.TeamManaged;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.config.ConfigHelper;
import wt.vc.views.View;
import wt.workflow.engine.WfProcess;

public class Resolution {
	
	public static String STATUTE_PATH = "/ptc/Windchill/codebase/ext/tianma/part/config/resolution.xlsx";
	
	/***
	 * 读取exce分辨率及分辨率代码
	 * @return
	 * @throws WTException 
	 */
	public static Map<String,String> getCascade() throws WTException {

		System.out.println("===>>start==>>action===>>");
		InputStream is = null;
		Workbook wb = null;
		Workbook workbook = null;
		try {
			System.out.println("CASCADE_PATH===>>" + STATUTE_PATH);
			is = new FileInputStream(STATUTE_PATH);

			System.out.println("=====>>>" + STATUTE_PATH);
			if (!is.markSupported()) {
				is = new PushbackInputStream(is, 8);
			}

			if (POIFSFileSystem.hasPOIFSHeader(is)) {
				// 2003及以下
				wb = new HSSFWorkbook(is);
			} else if (POIXMLDocument.hasOOXMLHeader(is)) {
				// 2007及以上
				wb = new XSSFWorkbook(is);
			} else {
				// 不是Excel
				throw new WTException("Incorrect configuration file path.");
			}

			workbook = wb;

			Sheet sheet = workbook.getSheetAt(0);
			Row row;
			Cell cell1,cell2,cell;
			String tempVal;

			Map<String,String> fblMap = new HashMap<String,String>();
			// 第一行为表头，从第二行开始遍历
			for (int i = 2, rowNum = sheet.getLastRowNum(); i <= rowNum; i++) {
				if ((row = sheet.getRow(i)) != null) {
					// 遍历列
					String finishedGoodResolutionCode = "";
					String fbl_W = "";
					int cellNum = row.getLastCellNum();
					String str = "";
					for (int j = 0; j <= cellNum; j++) {
						cell = row.getCell(j);
						cell1 = row.getCell(0);
						cell2 = row.getCell(1);
						if (cell1 == null || (tempVal = cell1.getStringCellValue()) == null||cell2 == null || (tempVal = cell2.getStringCellValue()) == null) {
							str = "";
						} else {
							finishedGoodResolutionCode = cell1.getStringCellValue();
							fbl_W = cell2.getStringCellValue();
							fblMap.put(fbl_W, finishedGoodResolutionCode);
						}
					}
				}
			}
			System.out.println("fblMap====>>>"+fblMap);
			return fblMap;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new WTException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new WTException(e);
		} finally {
			close(is);
		}
	}
	
	
	/***
	 * 遍历Map将分辨率属性写入到物料中
	 * @param part
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static void setAttsToIBA(WTPart parts) throws WTException, RemoteException {
		System.out.println("====start  设置分辨率===>>>");
		Map<String, String> ibaMap = getCascade();
		WTPart part = getLatestPart(parts);
		String versionPart1 = part.getVersionIdentifier().getValue();
		String versionPart = part.getIterationIdentifier().getValue();
		System.out.println("banben ==>>"+versionPart1+versionPart);
		System.out.println("+===>>"+isLatest(parts));
//		partCNAndENName = (String) IBAUtil.getIBAValue(part, "partCNAndENName");
		System.out.println("part number===>>"+part.getNumber()+"===>>"+versionPart);
		String resolution_H = (String) IBAUtil.getIBAValue(part, "ResolutionGateNew");// 分辨率(横)
		System.out.println("resolution_H===>>"+resolution_H);
		String resolution_H2 = (String) IBAUtil.getIBAValue(parts, "finishedGoodResolutionH");// 分辨率(横)
		System.out.println("resolution_H===>>"+resolution_H2);
		String resolution_W = (String) IBAUtil.getIBAValue(part, "ResolutionSourceNew");// 分辨率(竖)
		String resolution = resolution_H + "X" + resolution_W;
		System.out.println("resolution====>>"+resolution);
		System.out.println("ibaMap==>>"+ibaMap);
		Iterator keys = ibaMap.keySet().iterator(); 
		Hashtable<String, String> values = new Hashtable<String, String>();
		while(keys.hasNext()){  
		     String key = (String)keys.next();
		     if(key.equals(resolution)){  
		    	String value = ibaMap.get(key);
		    	System.out.println("value====>"+value);
		        System.out.println("存在key==");  
		        addToHashtable(values,"resolutionSourceCode", value);
				IBAUtil.setSoftTypeIBAValues(part, values);
				break;
		     } else {
		    	 addToHashtable(values,"resolutionSourceCode", "other");
				 System.out.println("values11===>>"+values);
				 IBAUtil.setSoftTypeIBAValues(part, values);
		     }
		} 

	}

	/**
	 * 关闭资源
	 * 
	 * @param closeable
	 */
	public static void close(Closeable closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void ReadExcel() {
		
	}
	/**
	 * 实现Hashtable添加数据时不会出现空指针异常
	 * 
	 * @param hashtable
	 * @param key
	 * @param value
	 * @return
	 */
	private static Hashtable<String, String> addToHashtable(Hashtable<String, String> hashtable, String key,
			String value) {
		if (key == null && hashtable != null) {
			return hashtable;
		}

		if (value == null && hashtable != null) {
			return hashtable;
		}

		if (key == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (value == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (hashtable == null) {
			hashtable = new Hashtable<String, String>();
		}
		hashtable.put(key, value);

		return hashtable;
	}

	public static void getNumberByPBO(WTObject object) {

		WTPart parts = null;
		if (object instanceof WTPart) {
			try {
				parts = (WTPart) object;
				WTPart part = getLatestPart(parts);
				String versionPart = part.getIterationIdentifier().getValue();
				String partCNAndENName = (String) IBAUtil.getIBAValue(part, "partEnvProtectionCategory");
				System.out.println("partNumber===>>"+part.getNumber()+":====>>>"+partCNAndENName);
				System.out.println("part number===>>" + part.getNumber() + "===>>" + versionPart);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (WTException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static WTPart getLatestPart(WTPart part) throws WTException {
		View view = (View) part.getView().getObject();
		WTPartConfigSpec configSpec = WTPartConfigSpec
				.newWTPartConfigSpec(WTPartStandardConfigSpec.newWTPartStandardConfigSpec(view, null));
		QueryResult qr = ConfigHelper.service.filteredIterationsOf(part.getMaster(), configSpec);
		return qr.hasMoreElements() ? (WTPart) qr.nextElement() : null;
	}
	
	/**
	 * 判断部件是否最新版本
	 * @param part
	 * @return
	 * @throws WTException
	 */
	public static boolean isLatest(WTPart part) throws WTException {
		boolean islatest = true;
		if(part == null){
			return islatest;
		}
		
		boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
		
		try {
			WTPart latest =  getLatestPart(part);
			
			//判断最新是否检出
			if(latest != null){
//				if(isCheckedOut(latest)){
//					throw new WTException("部件"+latest.getDisplayIdentity()+"被检出。");
//				}
				if(!part.equals(latest)){
					islatest = false;
				}
			}
			
		} finally{
			SessionServerHelper.manager.setAccessEnforced(flag);
		}
		
		return islatest;
	}
	
}
